package com.jyh.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jyh.blog.dao.FriendLinkDao;
import com.jyh.blog.dto.FriendLinkBackDTO;
import com.jyh.blog.dto.FriendLinkDTO;
import com.jyh.blog.entity.FriendLink;
import com.jyh.blog.service.FriendLinkService;
import com.jyh.blog.utils.BeanCopyUtils;
import com.jyh.blog.utils.PageUtils;
import com.jyh.blog.vo.ConditionVO;
import com.jyh.blog.vo.FriendLinkVO;
import com.jyh.blog.vo.LinkCheckVO;
import com.jyh.blog.vo.PageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

import static com.jyh.blog.constant.CommonConst.TRUE;

/**
 * (FriendLink)表服务实现类
 *
 * @author jyh
 * @since 2023-02-14 19:18:47
 */
@Service("friendLinkService")
public class FriendLinkServiceImpl extends ServiceImpl<FriendLinkDao, FriendLink> implements FriendLinkService {

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveOrUpdateLinks(FriendLinkVO friendLinkVO) {
        FriendLink friendLink = BeanCopyUtils.copyObject(friendLinkVO, FriendLink.class);
        //为空说明是第一次
        if(ObjectUtils.isEmpty(friendLink.getStatus())){
            friendLink.setStatus(TRUE);
        }
        this.saveOrUpdate(friendLink);
    }


    @Override
    public void linkCheck(LinkCheckVO linkCheckVO) {
        FriendLink friendLink = BeanCopyUtils.copyObject(linkCheckVO, FriendLink.class);
        this.updateById(friendLink);

    }

    @Override
    public PageResult<FriendLinkBackDTO> linkBackDTOList(ConditionVO conditionVO) {
        Page<FriendLink> page = new Page<>(PageUtils.getLimitCurrent(), PageUtils.getSize());
        this.page(page, new LambdaQueryWrapper<FriendLink>()
                .eq(StringUtils.hasText(conditionVO.getKeywords()), FriendLink::getName, conditionVO.getKeywords()));
        //转换格式
        List<FriendLinkBackDTO> friendLinkBackDTOS = BeanCopyUtils.copyList(page.getRecords(), FriendLinkBackDTO.class);
        return new PageResult<>(friendLinkBackDTOS, (int) page.getTotal());
    }
    @Override
    public void deleteLinks(List<String> idList) {
        this.removeByIds(idList);
    }

    @Override
    public List<FriendLinkDTO> homeLinks() {
        List<FriendLink> friendLinkList = this.list(new LambdaQueryWrapper<FriendLink>()
                .select(FriendLink::getId, FriendLink::getName, FriendLink::getAvatar, FriendLink::getAddress, FriendLink::getIntro)
                .eq(FriendLink::getStatus, TRUE)
        );
        return BeanCopyUtils.copyList(friendLinkList,FriendLinkDTO.class);
    }
}

